<?php
class SignInForm extends BaseForm {
  const FORM_NAME           = 'frm';

  const FIELD_USERNAME      = 'username';
  const FIELD_PASSWORD      = 'password';

  private $accessUserGroups = array();
  private $user             = null;

  public function  __construct($v) {
    $this->accessUserGroups = $v;

    parent::__construct();
  }

  public function configure() {

    $widgets = array(
            self::FIELD_USERNAME => new sfWidgetFormInput(array(), array()),
            self::FIELD_PASSWORD => new sfWidgetFormInputPassword(array(), array('maxlength' => 255))
    );

    $labels = array(
            self::FIELD_USERNAME => 'Username',
            self::FIELD_PASSWORD => 'Password'
    );

    $this->setWidgets($widgets);
    $this->widgetSchema->setLabels($labels);

    $validators = array(
            self::FIELD_USERNAME => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_USERNAME])))),
            self::FIELD_PASSWORD => new sfValidatorString(array(), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_PASSWORD]))))
    );

    $this->setValidators($validators);
    $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'postValidator'))));

    $this->widgetSchema->setNameFormat(self::FORM_NAME . '[%s]');

    $this->validatorSchema->setOption('allow_extra_fields', true);
    $this->validatorSchema->setOption('filter_extra_fields', false);
  }

  public function postValidator($validator, $values) {
    if (trim($values[self::FIELD_USERNAME]) != '' && trim($values[self::FIELD_PASSWORD]) != '') {
      $users = USERTable::getInstance()->findByUsername(trim($values[self::FIELD_USERNAME]));
      $user = $users[0];
      
      $error = new sfValidatorError($validator, 'Wrong Username and Password combination.');
      if (is_null($user) || !is_object($user) || !($user instanceof USER) || ($user instanceof USER && !in_array($user->getUserGroupId(), $this->accessUserGroups))) {
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_USERNAME => $error));
      } elseif (StringUtil::hashPassword(trim($values[self::FIELD_PASSWORD]), $user->getSalt()) !== $user->getPassword()) {
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_USERNAME => $error));
      }
      $this->user = $user;
    }

    return $values;
  }

  public function getUser() {
    return $this->user;
  }
}
?>